import java.util.HashSet;
import java.util.Set;

public class Solution1319 {
    public int makeConnected(int n, int[][] connections) {
        if (connections.length<n-1){
            return -1;
        }
        int[] b=new int[n];
        for (int i=0;i<n;i++){
            b[i]=i;
        }
        for (int[] connection : connections) {
            int x=find(b,connection[0]);
            int y=find(b,connection[1]);
            b[x]=y;
        }
        Set<Integer> set=new HashSet<>();
        for (int i=0;i<n;i++){
            set.add(find(b,i));
        }
        return set.size()-1;
    }

    private int find(int[] b, int i) {
        while (i!=b[i]){
            i=b[i];
        }
        return i;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1319().makeConnected(4,new int[][]{{0,1},{1,2},{0,2}}));
    }
}
